<template>
  <el-card class="box-card">
    <itable
    :table="tconfig.tableConfig"
    :tableData="tconfig.tableData"
    :page-bean="tconfig.pageBean"
    @pageChange="pageChange"
    @handelEdit="handelEdit"
    @handelDel="handelDel"
    >
      <template #danger_type_id="prop">
        <span>{{ filtStatus(prop.obj.row.danger_type_id) }}</span>
      </template>
      <template #searchBox>
        <Eform
          :model="form"
          :elem="fromData"
          :submit="true"
          :reset="true"
          :button="false"
          okIcon="Search"
          btnSize="default"
          submitText="搜索"
          @onSuccess="onSuccess"
          @onReset="onReset"
          >
        </Eform>
      </template>

      <template #headerbtn>
        <el-button type="primary" plain @click="chilkadd" icon="Plus">添加</el-button>
      </template>
    </itable>

    <el-dialog
    :title="type?'新增':'编辑'"
    v-model="dialogVisible"
    width="50%">
    <el-form :model="formInline" :rules="rules" ref="formRef" class="demo-form-inline">
      <el-form-item label="危险作业类名" prop="danger_type_id" style="width: 90%;">
        <el-select v-model="formInline.danger_type_id" filterable class="m-2" placeholder="请输入危险作业类名">
          <el-option
            v-for="item in option"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="危险作业安全条件" prop="content">
        <el-input v-model="formInline.content" :rows="2" type="textarea"/>
      </el-form-item>
      <el-form-item label="危险作业安全提醒">
        <TEditor :content="formInline.remind" ref="teditor"/>
      </el-form-item>
      <el-form-item label="音频内容">
        <upAudio @upload-success="handleSuccess" :audios="audios"/>
      </el-form-item>
      <el-form-item label="视频内容">
        <upload-video
          :videos="videos"
          :videoBaseUrl="IMAGEURL"
          @upload-success="videoSuccess" >
        </upload-video>
      </el-form-item>
      <el-form-item label="收看最小时长(秒)"  prop="min_view_time">
        <el-input-number v-model="formInline.min_view_time" :min="0" />
      </el-form-item>
  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(formRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      </span>
    </template>
  </el-dialog>
  </el-card>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue';
import { PageBean } from "@/utils/page-bean";
import useCurrentInstance from '@/utils/useCurrentInstance'
import itable from '@/components/table/table.vue'
import Eform from '@/components/eform/index.vue';
import TEditor from '@/components/TEditor.vue';
import type { FormInstance } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import UploadVideo from '@/components/upVideo.vue'
import upAudio from '@/components/upAudio.vue';

const { proxy } = useCurrentInstance()
const teditor = ref()
const formRef = ref<FormInstance>()
const IMAGEURL = ref('')
let audios = ref([]) as any
let videos = ref([]) as any
let dialogVisible = ref(false)
let option:any = ref([])
let type = ref(true)
let formInline = reactive({
  danger_type_id:'',
  content:'',
  min_view_time:'30',
  audio:'',
  video:'',
  remind:''
})
const rules = reactive({
  danger_type_id: [
    { required: true, message: '请选择危险作业类名', trigger: 'change' },
  ]
})
let fromData = reactive([
  {
    label: "危险作业种类",
    prop: "danger_type_id",
    element:'select',
    labelWidth:'120',
    filterable:true,
    clearable: true,
    optlabel:'name',
    optvalue:'id',
    option:option
  }
])
let info = reactive([
  {label:'员工信息',value:'',phone:'',prop:'staff'},
  {label:'危险作业种类',value:'',prop:'danger_name'},
  {label:'陪同作业人',value:'',prop:'chaperone'},
  {label:'作业区域',value:'',prop:'area'},
  {label:'作业名称',value:'',prop:'name'},
  {label:'记录时间',value:'',prop:'created_at'},
  {label:'是否进行安全教育',value:'',prop:'is_security'},
  {label:'是否完成审批',value:'',prop:'is_check'},
  {label:'',template:'img',value:[''],prop:'file'}
])
let form = reactive({
  page:1,
  size:10,
  danger_type_id:''
})

const tconfig = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})

// 重置
const onReset = () => {
  tconfig.pageBean.pageIndex = 1
  getRecordDanger()
}
// 搜索
const onSuccess = () => {
  tconfig.pageBean.pageIndex = 1
  getRecordDanger()
}

// 新增
const chilkadd = () => {
  type.value = true
  dialogVisible.value = true
  formInline.danger_type_id = ''
  formInline.content = ''
  formInline.min_view_time = '30'
  formInline.remind = ''
  formInline.video = ''
  formInline.audio = ''
  audios.value = []
  videos.value = []
}

// 表格-编辑
const handelEdit = (a, b, id) => {
  type.value = false
  dialogVisible.value = true
  proxy.$api.getNewDangerDetails({id:b.id}).then(res => {
    formInline.id = res.result.id
    for(let key in formInline){
      formInline[key] = res.result[key]
    }
    let url1 = res.result.audio
    let url2 = res.result.video
    audios.value = url1.indexOf('http') !== -1 ? [{name:url1.substring(url1.lastIndexOf('/')+1),url:res.result.audio}] : []
    videos.value = url2.indexOf('http') !== -1 ? [{name:url2.substring(url2.lastIndexOf('/')+1),url:res.result.video}] : []
  })
}
// 表格-删除
const handelDel = (a, b, id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getDangerDelete({id:b.id}).then(res => {
      if(res.code == 200){
        proxy.$message.success(res.msg)
        getRecordDanger()
      }
    })
  }).catch(() => {
    proxy.$message({
      type: 'info',
      message: '已取消删除',
    })
  })

}
// 上传音频成功
const handleSuccess = (url) => {
  formInline.audio = url
}
// 上传视频成功
const videoSuccess = (url) => {
  formInline.video = url
}
// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  formInline.remind = teditor.value.content
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if(type.value){
        proxy.$api.getDangerCreate(formInline).then(res => {
          if(res.code == 200){
            proxy.$message.success(res.msg)
            formEl.resetFields()
            dialogVisible.value = false
            getRecordDanger()
          }
        })
      }else{
        proxy.$api.getDangerUpdate(formInline).then(res => {
          if(res.code == 200){
            proxy.$message.success(res.msg)
            formEl.resetFields()
            dialogVisible.value = false
            getRecordDanger()
          }
        })
      }
    } else {
      return false
    }
  })
}
// 清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  teditor.value.remind = ''
  dialogVisible.value = false
}

// 分页
const pageChange = () => {
  getRecordDanger()
}
// 台账列表
const getRecordDanger = () => {
  tconfig.tableConfig.loading = true
  form.page = tconfig.pageBean.pageIndex
  proxy.$api.getDangerList(form).then(res =>{
    tconfig.tableData=res.result.lists
    tconfig.tableConfig.loading = false
    tconfig.pageBean.Total=res.result.total_rows
  }).catch(err => tconfig.tableConfig.loading = true)
}
const getCommonDanger = () => {
  option.value = []
  proxy.$api.getCommonDanger().then(res => {
    option.value = res.result
  })
}
getCommonDanger()
getRecordDanger()
const filtStatus = (id) => {
  let val = ''
  option.value.map(item => {
    if(item.id == id){
      val = item.name
    }else{
      val = '-'
    }
  })
  return val
}
// 初始化表格
const initTable = () => {
tconfig.tableConfig = {
  loading: true,
  hasSelect: false,
  hasIndex: true,
  hasOperation: true,
  hasSearch: true,
  hasPage: true,
  headerShowBtn:true,
  tr: [
    {
      label: "危险作业种类",
      prop: "danger_type_name",
    }
  ],
  operation:{
    label:'操作',
    width:'500',
    data:[
      { label:'编辑', type:'', icon:'EditPen', Fun:'handelEdit', id: 1 },
      { label:'删除', type:'danger', icon:'Delete', Fun:'handelDel', id: 2 }
    ]
  }
}
}
initTable()
</script>

<style lang='scss' scoped>
:deep(.el-dialog__body){
.el-form>.el-form-item{
  width: 90%;
  margin-bottom: 20px;
  margin-left: 10px;
}
.el-select{
  width: 100%;
}
}
.dialog-footer{
  width: 100%;
  display: flex;
  justify-content: center;
  .el-button{
    width: 15%;
  }
}
</style>
